package com.ffzx.commerce.framework.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.ftp.session.FtpFileInfo;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;

public class FTPUtil {

	private final static Logger logger = LoggerFactory.getLogger(FTPUtil.class);
	
	/**
	 * Ftp上传封装类,上传文件名称使用fptFile名称
	 * @param ftpChannel
	 * @param fptFile
	 * @param ftpServerPath
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static boolean ftpUpload(MessageChannel ftpChannel,File fptFile, String ftpServerPath) throws Exception{
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		//new String(ftpServerPath.getBytes(Charset.forName("UTF-8")),"ISO-8859-1")
		Message<File> message = MessageBuilder.withPayload(fptFile)
				.setHeader("remote_dir", ftpServerPath)
				.setHeader("remote_filename", fptFile.getName()).build();
		return ftpChannel.send(message);
	}
	
	/**
	 * Ftp上传封装类,上传文件名称使用ftpFileName名称(重命名)
	 * @param ftpChannel
	 * @param ftpFile
	 * @param ftpFileName
	 * @param ftpServerPath
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static boolean ftpUpload(MessageChannel ftpChannel,File ftpFile,String ftpFileName, String ftpServerPath) throws Exception {
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		Message<File> message = MessageBuilder.withPayload(ftpFile)
				.setHeader("remote_dir", ftpServerPath)
				.setHeader("remote_filename", ftpFileName).build();
		return ftpChannel.send(message);
	}
	
	/**
	 * Ftp上传封装类,上传文件名称使用ftpFileName名称(重命名)
	 * @param ftpChannel
	 * @param fileInputStream
	 * @param ftpFileName
	 * @param ftpServerPath
	 * @return
	 * @throws Exception
	 */
	public static boolean ftpUpload(MessageChannel ftpChannel,InputStream fileInputStream,String ftpFileName, String ftpServerPath) throws Exception {
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		Message<byte[]> message=null;
		try {
			message = MessageBuilder.withPayload(IOUtils.toByteArray(fileInputStream))
					.setHeader("remote_dir", ftpServerPath)
					.setHeader("remote_filename", ftpFileName).build();
		} catch (IOException e) {
			logger.error("ftp上传产生异常",e);
			throw new Exception(e);
		} finally{
			IOUtils.closeQuietly(fileInputStream);
		}
		return ftpChannel.send(message);
	}
	
	/**
	 * Ftp上传封装类,上传文件名称使用ftpFileName名称(重命名)
	 * @param ftpChannel
	 * @param byteArray
	 * @param ftpFileName
	 * @param ftpServerPath
	 * @return
	 * @throws Exception
	 */
	public static boolean ftpUpload(MessageChannel ftpChannel,byte[] byteArray,String ftpFileName, String ftpServerPath) throws Exception {
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		Message<byte[]> message=null;
		message = MessageBuilder.withPayload(byteArray)
				.setHeader("remote_dir", ftpServerPath)
				.setHeader("remote_filename", ftpFileName).build();
		return ftpChannel.send(message);
	}
	
	/**
	 * ftp 删除图片
	 * 
	 * @param ftpChannel
	 * @param ftpFileName
	 * @param ftpServerPath
	 * @return
	 * @throws Exception
	 */
	public static boolean ftpRemove(MessageChannel ftpChannel,String ftpFileName, String ftpServerPath) throws Exception{
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		Message<String> message = null;
		try {
			message = MessageBuilder.withPayload(ftpFileName)
					.setHeader("file_remoteDirectory", ftpServerPath)
					.setHeader("file_remoteFile", ftpFileName)
					.build();
		} catch (Exception e) {
			logger.error("ftp删除产生异常",e);
			throw new Exception(e);
		}
		logger.info("删除ftp：getHeaders="+message.getHeaders());
		return ftpChannel.send(message);
	}
	
	/**
	 * ftp 下载图片
	 * 
	 * @param ftpChannel
	 * @param ftpFileName
	 * @param ftpServerPath
	 * @return
	 * @throws Exception
	 */
	public static boolean ftpDownload(MessageChannel ftpChannel,String ftpFileName ,String ftpServerPath) throws Exception{
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		Message<String> message = null;
		try {
			message = MessageBuilder.withPayload(ftpFileName)
					.setHeader("file_remoteDirectory", ftpServerPath)
					.setHeader("file_remoteFile", ftpFileName)
					.build();
		} catch (Exception e) {
			logger.error("ftp下载产生异常",e);
			throw new Exception(e);
		}
		logger.info("ftp下载：getHeaders="+message.getHeaders());
		return ftpChannel.send(message);
	}
	
	/**
	 * ftp 列举文件
	 * 
	 * @param ftpChannel
	 * @param ftpFileName
	 * @param ftpServerPath
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<String> ftpFileList(MessageChannel ftpChannel, QueueChannel queueChannel, String ftpServerPath) throws Exception{
		if (StringUtils.isNotBlank(ftpServerPath) && ftpServerPath.startsWith("/")) {
			ftpServerPath = StringUtils.substringAfter(ftpServerPath, "/");
		}
		List<String> fileList = new ArrayList<String>();
		try {
			ftpChannel.send(MessageBuilder.withPayload(ftpServerPath).build());
			List<Message<?>> messageList = queueChannel.purge(null);
			for(Message<?> message : messageList){
				List<FtpFileInfo> ffiList = (List<FtpFileInfo>)message.getPayload();
				for(FtpFileInfo ffi : ffiList){
					fileList.add(ffi.getRemoteDirectory() + ffi.getFilename());
				}
			}
		} catch (Exception e) {
			logger.error("ftp列举文件异常",e);
			throw new Exception(e);
		}
		return fileList;
	}

}
